package com.recharge.job;

import com.alibaba.fastjson.JSON;
import com.recharge.AsyncTaskService;
import com.recharge.domain.TradeFlow;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.ITradeFlowMapper;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.utils.OrderStatus;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by CAOQI on 2017/1/8.
 */
@Service
public class QueryOrderService {

    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    @Autowired
    private ITradeFlowMapper iTradeFlowMapper;

    @Autowired
    private AsyncTaskService asyncTaskService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public void queryOrder(){
        TradeOrder queryCondition = new TradeOrder();
        queryCondition.setOrderStatus((short) OrderStatus.PROCESSING);
//        拿到住订单列表 充值状态为1 待充值
        List<TradeOrder> tradeOrders = iTradeOrderMapper.selectTimeOutList(queryCondition, 20);

        if (CollectionUtils.isEmpty(tradeOrders)){
            queryCondition.setOrderStatus((short) OrderStatus.UNKNOWN);
            tradeOrders = iTradeOrderMapper.selectOldTimeOutList(queryCondition, 20);
        }

        for (TradeOrder tradeOrder : tradeOrders){
            try {
                TradeFlow tradeFlow = iTradeFlowMapper.selectByOrderId(tradeOrder.getOrderStatus(),tradeOrder.getOrderId());

                logger.info("query info .orderId:{},flow:{}",tradeOrder.getOrderId(), JSON.toJSONString(tradeFlow));

                asyncTaskService.query(tradeOrder,tradeFlow);

                iTradeOrderMapper.updateQueryCount(tradeOrder.getOrderId());
            } catch (Exception e) {
                logger.info("{}",tradeOrder.getOrderId(),e);
            }
        }
    }
}
